package models

import (
	"gorm.io/gorm"
)

type Article struct {
	gorm.Model
	Title   string `gorm:"type:varchar(20);not null;comment:标题" json:"title"`
	Content string `gorm:"type:text;not null;comment:标题" json:"content"`
}

// 添加
func (a *Article) Creat() error {
	return DB.Create(&a).Error
}

// 列表+模糊搜索
func (a *Article) List(title string, page, pageSize int) (articles []*Article, err error) {
	err = DB.Where("title like ?", "%"+title+"%").Scopes(Paginate(page, pageSize)).Find(&articles).Error
	return
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		//q := r.URL.Query()
		//page, _ := strconv.Atoi(q.Get("page"))
		if page <= 0 {
			page = 1
		}

		//pageSize, _ := strconv.Atoi(q.Get("page_size"))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize //偏移量
		return db.Offset(offset).Limit(pageSize)
	}
}
